package com.chuzhiyun.chengguoxy.feature.login;

import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import okhttp3.Cookie;
import okhttp3.HttpUrl;

import android.content.Intent;
import android.view.View;
import com.chuzhiyun.chengguoxy.databinding.ActivitySmsCodeBinding;
import com.chuzhiyun.chengguoxy.feature.base.BaseActivity;
import com.chuzhiyun.chengguoxy.feature.bean.UserInfoBean;
import com.chuzhiyun.chengguoxy.feature.home.HomeActivity;
import com.chuzhiyun.chengguoxy.global.Config;
import com.chuzhiyun.chengguoxy.network.NetApi;
import com.chuzhiyun.chengguoxy.network.NetService;
import com.chuzhiyun.chengguoxy.network.StringNetCallback;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.utlis.StringUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.store.CookieStore;
import com.vondear.rxtool.RxSPTool;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("StatementWithEmptyBody")
public class SmsCodeActivity extends BaseActivity<ActivitySmsCodeBinding> {

    private String mPhoneNumber;
    private  Integer TimeCount = 0;
    private Disposable mDisposable;

    @Override
    public void initView(View view) {

    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        mPhoneNumber = getIntent().getStringExtra("mPhoneNumber");
        sendCode(mPhoneNumber);
        viewBinding.sendText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                startInterval();
            }
        });

        viewBinding.submitText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                loginClick();
            }
        });

        startInterval();
    }

    private void startInterval() {
        int count = 60;
        if (TimeCount==0){
            count = 60;
        }else {
            count = 60 - TimeCount;
        }
        int finalCount = count;
        Observable.interval(1, TimeUnit.SECONDS)
                .take(count)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NotNull Long aLong) {
                        viewBinding.sendText.setEnabled(false);
                        viewBinding.sendText.setText(String.format("发送（%ss）", finalCount - aLong));
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        viewBinding.sendText.setEnabled(true);
                        viewBinding.sendText.setText("重新发送");
                        TimeCount = 0;
                    }
                });
    }

    private void loginClick(){
        String code = viewBinding.codeView.getInputContent();
        if (StringUtils.isBlank(code)||code.length()<6){
            return;
        }
        showLoadingDialog();
        String url = NetApi.postSMSLogin();
        HashMap<String,String>param = new HashMap<>();
        param.put("mobile",mPhoneNumber);
        param.put("code",code);
        NetService.getInstance().postParam(url, param, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                dismissLoadingDialog();
                System.out.println(response);
                if (statusCode==204){
                    CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
                    System.out.println(cookieStore);

                    List<Cookie> cookies = cookieStore.getCookie(HttpUrl.parse(NetApi.Base_URL));
                    Cookie cookie = cookies.get(0);
                    System.out.println(cookie);
                    String token = cookie.value();
                    System.out.println(token);
                    RxSPTool.putString(mContext, Config.SP_TOKEN,token);

                    startActivity(new Intent(SmsCodeActivity.this, HomeActivity.class));
                    finish();
                    getUserInfo();
                }
            }

            @Override
            public void onError(String error) {
                dismissLoadingDialog();
                System.out.println(error);
            }
        });
    }

    private void sendCode(String phoneStr){

        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        cookieStore.removeAllCookie();

        String url = NetApi.postSendSMSCode();
        HashMap<String,String>param = new HashMap<>();
        param.put("mobile",phoneStr);
        NetService.getInstance().postParam(url, param, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                if (statusCode==204){

                }
                if (statusCode==403){

                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    private void saveToken(){
        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        System.out.println(cookieStore);

        List<Cookie> cookies = cookieStore.getCookie(HttpUrl.parse(NetApi.Base_URL));
        Cookie cookie = cookies.get(0);
        System.out.println(cookie);
        String token = cookie.value();
        System.out.println(token);
    }

    private void getUserInfo(){
        saveToken();

        String url = NetApi.getStudentInfo();
        NetService.getInstance().get(url, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
                if (statusCode==200){
                    Gson gson = new Gson();
                    UserInfoBean bean = gson.fromJson(response,UserInfoBean.class);
                    System.out.println(bean);
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    @Override
    protected ActivitySmsCodeBinding getViewBinding() {
        return ActivitySmsCodeBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

}